package com.blb.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.blb.entity.Menu;
import com.blb.mapper.MenuExtMapper;
import com.blb.utils.SessionUtils;

@Controller
public class LoginController {
	
	@Autowired
	private MenuExtMapper menuExtMapper;
	
	@RequestMapping("login")
	public String login(String username, String password, RedirectAttributes model, HttpSession httpSession) throws IOException{
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			// 登录
			subject.login(token);
		} catch (UnknownAccountException uae) {
			model.addFlashAttribute("msg", "用户名不存在");




			return "redirect:/";
		} catch (IncorrectCredentialsException ice) {
			model.addFlashAttribute("msg", "密码错误");
			return "redirect:/";
		} catch (LockedAccountException lae) {
			model.addFlashAttribute("msg", "账号被锁定");
			return "redirect:/";
		} catch (AuthenticationException ae) {
			model.addFlashAttribute("msg", ae.getMessage());
			return "redirect:/";
		}
		if (subject.isAuthenticated()) {
			System.out.println("登录成功");
		}
		return "redirect:/index";
	}
	
	/**
	 * 首页
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("index")
	public String index(Model model) throws IOException{
		//查询左侧菜单
		List<Menu> list = menuExtMapper.getMenusByUserId(SessionUtils.getUserId(), "0", "目录");
		
		model.addAttribute("menus", list);
		return "index";
	}

}
